﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using SHomeWorkshop.LunarPresentation.Adorners;
using System;
using System.Collections.Generic;
using Microsoft.Win32;
using System.IO;
using System.Reflection;
using System.Text;

namespace SHomeWorkshop.LunarPresentation.Dialogs
{
    /// <summary>
    /// PrintPriviewSettingDialog.xaml 的交互逻辑
    /// </summary>
    public partial class PageSettingDialog : Window
    {
        public PageSettingDialog(Editor masterEditor)
        {
            InitializeComponent();

            if (masterEditor == null)
            {
                throw new Exception("masterEditor参数不能为null。");
            }

            this.masterEditor = masterEditor;
        }

        private Editor masterEditor;

        public Editor MasterEditor
        {
            get { return masterEditor; }
        }

        private void btnPreviewAndPrint_Click(object sender, RoutedEventArgs e)
        {
            if (masterEditor == null) return;

            if ((masterEditor.DefaultBackground != Brushes.White &&
                masterEditor.DefaultBackground != Brushes.Transparent) ||
                masterEditor.ExFontSize > 14)
            {
                MessageBoxResult r = Dialogs.LunarMsgBox.MsgBoxShow(
                    Globals.appName,
                    "打印当前文档会较浪费打印机耗材，真的要继续打印吗？",
                    "当前文档背景色不是白色或透明色，或者字号大于14，这样打印会严重浪费打印耗材。",
                    "您可以考虑先将编辑器配色方案改为白底黑字（命令：bdhz）或缩小字号再打印。\r\n" +
                    "——要缩小字号，请将主界面右下角的“字号缩放滑块条”拖动到最左侧。",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Warning);
                if (r != MessageBoxResult.Yes) return;
            }

            if (UpdatePageSettingIntoToDocument())
            {
                //打印由Cmmands.PreviewAndPrintDocument()方法来完成。此对话框也由此方法调用。
                this.DialogResult = true;
                this.Close();
                Commands.Command.PreviewAndPrintDocument(this.masterEditor);
            }
        }

        //private static Thickness defImagePrintingMargin =
        //    new Thickness(
        //        1.0 * ratioValueFromMmToWpfPixcelUnits,
        //        1.0 * ratioValueFromMmToWpfPixcelUnits,
        //        1.0 * ratioValueFromMmToWpfPixcelUnits,
        //        1.0 * ratioValueFromMmToWpfPixcelUnits
        //        );

        //private Thickness ImagePrintingMaring
        //{
        //    get
        //    {
        //        try
        //        {
        //            double left = double.Parse(tbxMarginLeft.Text) * ratioValueFromMmToWpfPixcelUnits;
        //            double top = double.Parse(tbxMarginTop.Text) * ratioValueFromMmToWpfPixcelUnits;
        //            double right = double.Parse(tbxMarginRight.Text) * ratioValueFromMmToWpfPixcelUnits;
        //            double bottom = double.Parse(tbxMarginBottom.Text) * ratioValueFromMmToWpfPixcelUnits;

        //            PaperInfo curPaperInfo = PaperInfo.GetPaperInfo(
        //                    masterEditor.PaperSizeLineAdorner.PaperName);

        //            if (masterEditor.PaperSizeLineAdorner.PaperDirection == Orientation.Vertical)
        //            {
        //                if (left + right > curPaperInfo.ShortSideWPFUnit)
        //                {
        //                    Exception ex = new Exception("左边距加右边距的值大于宽度！");
        //                    throw ex;
        //                }

        //                if (top + bottom > curPaperInfo.LongSideWPFUnit)
        //                {
        //                    Exception ex = new Exception("左边距加右边距的值大于高度！");
        //                    throw ex;
        //                }
        //            }
        //            else
        //            {
        //                if (left + right > curPaperInfo.LongSideWPFUnit)
        //                {
        //                    Exception ex = new Exception("左边距加右边距的值大于宽度！");
        //                    throw ex;
        //                }

        //                if (top + bottom > curPaperInfo.ShortSideWPFUnit)
        //                {
        //                    Exception ex = new Exception("左边距加右边距的值大于高度！");
        //                    throw ex;
        //                }
        //            }

        //            return new Thickness(left, top, right, bottom);
        //        }
        //        catch (Exception ex)
        //        {
        //            Dialogs.LunarMsgBox.MsgBoxShow(
        //                Globals.appName,
        //                "发生意外，页边距值设置错误！将取默认值！", "异常信息如下：\r\n" + ex.Message,
        //                ex.StackTrace, MessageBoxButton.OK, MessageBoxImage.Warning);
        //            return defImagePrintingMargin;
        //        }
        //    }
        //}

        private void rbtnHorizontalPaper_Checked(object sender, RoutedEventArgs e)
        {
            paperSampleRectangle.Height = 50;
            paperSampleRectangle.Width = 70;

            RefreshPaperSizeLineOfEditor();
        }

        private void rbtnVerticalPaper_Checked(object sender, RoutedEventArgs e)
        {
            paperSampleRectangle.Height = 70;
            paperSampleRectangle.Width = 50;

            RefreshPaperSizeLineOfEditor();
        }

        private void ckxShowPaperSizeLine_Checked(object sender, RoutedEventArgs e)
        {
            RefreshPaperSizeLineOfEditor();
        }

        private void ckxShowPaperSizeLine_Unchecked(object sender, RoutedEventArgs e)
        {
            RefreshPaperSizeLineOfEditor();
        }

        private void RefreshPaperSizeLineOfEditor()
        {
            if (masterEditor == null) return;

            if (tbxMarginLeft.Text.Length <= 0 || tbxMarginRight.Text.Length <= 0 ||
                tbxMarginTop.Text.Length <= 0 || tbxMarginBottom.Text.Length <= 0) return;

            if (ckxShowPaperSizeLine.IsChecked == true)
            {
                masterEditor.PaperSizeLineAdorner.PaperName = (cmbPaperType.SelectedItem as ComboBoxItem).Tag.ToString();
                if (rbtnHorizontalPaper.IsChecked == true)
                {
                    masterEditor.PaperSizeLineAdorner.PaperDirection = Orientation.Horizontal;
                }
                else if (rbtnVerticalPaper.IsChecked == true)
                {
                    masterEditor.PaperSizeLineAdorner.PaperDirection = Orientation.Vertical;
                }

                Thickness newMargin = new Thickness(
                     double.Parse(tbxMarginLeft.Text) * PaperInfo.ratioValueFromMmToWpfPixcelUnits,
                     double.Parse(tbxMarginTop.Text) * PaperInfo.ratioValueFromMmToWpfPixcelUnits,
                     double.Parse(tbxMarginRight.Text) * PaperInfo.ratioValueFromMmToWpfPixcelUnits,
                     double.Parse(tbxMarginBottom.Text) * PaperInfo.ratioValueFromMmToWpfPixcelUnits
                 );

                PaperInfo pi = PaperInfo.GetPaperInfo((cmbPaperType.SelectedItem as ComboBoxItem).Tag as string);

                if (rbtnHorizontalPaper.IsChecked == true)//纸张为横向
                {
                    if (newMargin.Left + newMargin.Right >= pi.LongSideWPFUnit / 2)
                    {
                        MessageBox.Show("左右页边距之和过大。应小于页面宽度的一半。",
                            Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (newMargin.Top + newMargin.Bottom >= pi.ShortSideWPFUnit / 2)
                    {
                        MessageBox.Show("上下页边距之和过大。应小于页面高度的一半。",
                            Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }
                else
                {
                    if (newMargin.Left + newMargin.Right >= pi.ShortSideWPFUnit / 2)
                    {
                        MessageBox.Show("左右页边距之和过大。应小于页面宽度的一半。",
                            Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (newMargin.Top + newMargin.Bottom >= pi.LongSideWPFUnit / 2)
                    {
                        MessageBox.Show("上下页边距之和过大。应小于页面高度的一半。",
                            Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }

                masterEditor.PaperSizeLineAdorner.PageMargin = newMargin;

                masterEditor.PaperSizeLineAdorner.ShowPaperSizeLine(true);
            }
            else
            {
                masterEditor.PaperSizeLineAdorner.ShowPaperSizeLine(false);
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        private void cmbPaperType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbPaperType.SelectedIndex < 0) return;

            RefreshPaperSizeLineOfEditor();
        }

        private void sliderV_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (slidersInitialized == false || masterEditor == null) return;

            masterEditor.BaseScrolledViewer.ScrollToVerticalOffset(sliderV.Value);
        }

        private void sliderH_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (slidersInitialized == false) return;
            masterEditor.BaseScrolledViewer.ScrollToHorizontalOffset(sliderH.Value);
        }

        private bool slidersInitialized = false;

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeSlidersValues();
            ckxShowPaperSizeLine.IsChecked = true;

            if (masterEditor != null)
            {
                //读取所有属性的值。
                ckxHorizontalCenter.IsChecked = masterEditor.PageSettingInfo.HorizontalCenter;
                ckxVerticalCenter.IsChecked = masterEditor.PageSettingInfo.VerticalCenter;

                tbxMarginTop.Text = (masterEditor.PageSettingInfo.MarginTop
                    / PaperInfo.ratioValueFromMmToWpfPixcelUnits).ToString("F1");
                tbxMarginBottom.Text = (masterEditor.PageSettingInfo.MarginBottom
                    / PaperInfo.ratioValueFromMmToWpfPixcelUnits).ToString("F1");
                tbxMarginLeft.Text = (masterEditor.PageSettingInfo.MarginLeft
                    / PaperInfo.ratioValueFromMmToWpfPixcelUnits).ToString("F1");
                tbxMarginRight.Text = (masterEditor.PageSettingInfo.MarginRight
                    / PaperInfo.ratioValueFromMmToWpfPixcelUnits).ToString("F1");

                foreach (ComboBoxItem ci in cmbPaperType.Items)
                {
                    if (ci.Tag.ToString() == masterEditor.PageSettingInfo.PaperName)
                    {
                        cmbPaperType.SelectedItem = ci;
                        break;
                    }
                }

                if (masterEditor.PageSettingInfo.PaperDirection == Orientation.Horizontal)
                {
                    rbtnHorizontalPaper.IsChecked = true;
                }
                else
                {
                    rbtnVerticalPaper.IsChecked = true;
                }
            }
        }

        private void InitializeSlidersValues()
        {
            if (masterEditor != null)
            {
                sliderH.Minimum = 0;
                sliderH.Maximum = masterEditor.BaseScrolledViewer.ScrollableWidth;
                sliderH.Value = masterEditor.BaseScrolledViewer.HorizontalOffset;

                sliderV.Minimum = 0;
                sliderV.Maximum = masterEditor.BaseScrolledViewer.ScrollableHeight;
                sliderV.Value = masterEditor.BaseScrolledViewer.VerticalOffset;

                slidersInitialized = true;
            }
        }

        private void btnMaxMainWindow_Click(object sender, RoutedEventArgs e)
        {
            if (Globals.MainWindow != null) Globals.MainWindow.WindowState = WindowState.Maximized;
            InitializeSlidersValues();
        }

        private void btnOutputSplitImages_Click(object sender, RoutedEventArgs e)
        {
            if (UpdatePageSettingIntoToDocument())
            {
                this.DialogResult = true;
                this.Close();
                Commands.Command.OutportSplitedImages(this.masterEditor);
            }
        }

        private static string numbers = "1234567890.";

        private void tbxMarginTop_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (numbers.Contains(e.Text) == false)
            {
                MessageBox.Show("只能输入半角数字和小数点。", Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                e.Handled = true;
                return;
            }
        }

        private void tbxMarginBottom_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (numbers.Contains(e.Text) == false)
            {
                MessageBox.Show("只能输入半角数字和小数点。", Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                e.Handled = true;
                return;
            }
        }

        private void tbxMarginLeft_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (numbers.Contains(e.Text) == false)
            {
                MessageBox.Show("只能输入半角数字和小数点。", Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                e.Handled = true;
                return;
            }
        }

        private void tbxMarginRight_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (numbers.Contains(e.Text) == false)
            {
                MessageBox.Show("只能输入半角数字和小数点。", Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                e.Handled = true;
                return;
            }
        }

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            if (UpdatePageSettingIntoToDocument())
            {
                this.DialogResult = true;
                this.Close();
            }
        }

        private bool UpdatePageSettingIntoToDocument()
        {
            if (tbxMarginLeft.Text.Length <= 0 || tbxMarginRight.Text.Length <= 0 ||
                tbxMarginTop.Text.Length <= 0 || tbxMarginBottom.Text.Length <= 0)
            {

                MessageBoxResult result = MessageBox.Show(
                    "某个页边距未设定值。点击“是（Yes）”会设定为默认值：0，否则请点击“否（No）”。",
                    Globals.appName, MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);

                if (result == MessageBoxResult.Yes)
                {
                    if (tbxMarginLeft.Text.Length <= 0)
                    {
                        tbxMarginLeft.Text = "0";
                    }

                    if (tbxMarginRight.Text.Length <= 0)
                    {
                        tbxMarginRight.Text = "0";
                    }

                    if (tbxMarginTop.Text.Length <= 0)
                    {
                        tbxMarginTop.Text = "0";
                    }

                    if (tbxMarginBottom.Text.Length <= 0)
                    {
                        tbxMarginBottom.Text = "0";
                    }
                }
                else return false;
            }

            PageSettings ps = new PageSettings();

            if (ckxVerticalCenter.IsChecked == true) { ps.VerticalCenter = true; }
            else { ps.VerticalCenter = false; }

            ps.HorizontalCenter = (ckxHorizontalCenter.IsChecked == true);
            ps.VerticalCenter = (ckxVerticalCenter.IsChecked == true);

            ps.MarginLeft = double.Parse(tbxMarginLeft.Text) * PaperInfo.ratioValueFromMmToWpfPixcelUnits;
            ps.MarginRight = double.Parse(tbxMarginRight.Text) * PaperInfo.ratioValueFromMmToWpfPixcelUnits;
            ps.MarginTop = double.Parse(tbxMarginTop.Text) * PaperInfo.ratioValueFromMmToWpfPixcelUnits;
            ps.MarginBottom = double.Parse(tbxMarginBottom.Text) * PaperInfo.ratioValueFromMmToWpfPixcelUnits;

            ps.PaperName = (cmbPaperType.SelectedItem as ComboBoxItem).Tag as string;
            ps.PaperDirection = (rbtnHorizontalPaper.IsChecked == true ? Orientation.Horizontal : Orientation.Vertical);

            //应改在Editor中实现。
            //masterEditor.PaperSizeLineAdorner.PageMargin = new Thickness(
            //ps.MarginLeft, ps.MarginRight, ps.MarginTop, ps.MarginBottom);

            PaperInfo pi = PaperInfo.GetPaperInfo(ps.PaperName);

            if (ps.PaperDirection == Orientation.Vertical)
            {
                if (ps.MarginLeft + ps.MarginRight >= pi.ShortSideWPFUnit / 2)
                {
                    MessageBox.Show("左右页边距过大，已超过所设置的页面的总宽度的一半！",
                        Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }

                if (ps.MarginTop + ps.MarginBottom >= pi.LongSideWPFUnit / 2)
                {
                    MessageBox.Show("上下页边距过大，已超过所设置的页面的总高度的一半！",
                        Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }
            }
            else
            {
                if (ps.MarginLeft + ps.MarginRight >= pi.LongSideWPFUnit / 2)
                {
                    MessageBox.Show("左右页边距过大，已超过所设置的页面的总宽度的一半！",
                        Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }

                if (ps.MarginTop + ps.MarginBottom >= pi.ShortSideWPFUnit / 2)
                {
                    MessageBox.Show("上下页边距过大，已超过所设置的页面的总高度的一半！",
                        Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }
            }

            string newPageSettingInfoSource = ps.ToString();

            ModifingItem mi = new ModifingItem();

            Action actPPS = new Action(null, -1, null, null, masterEditor.PageSettingInfo.ToString(),
               newPageSettingInfoSource, ActionType.PageSetting, null);

            masterEditor.PageSettingInfoSource = ps.ToString();

            mi.Add(actPPS);

            masterEditor.Do(mi);
            masterEditor.IsModified = true;

            return true;
        }

        private void tbxMarginTop_TextChanged(object sender, TextChangedEventArgs e)
        {
            RefreshPaperSizeLineOfEditor();
        }

        private void tbxMarginBottom_TextChanged(object sender, TextChangedEventArgs e)
        {
            RefreshPaperSizeLineOfEditor();
        }

        private void tbxMarginLeft_TextChanged(object sender, TextChangedEventArgs e)
        {
            RefreshPaperSizeLineOfEditor();
        }

        private void tbxMarginRight_TextChanged(object sender, TextChangedEventArgs e)
        {
            RefreshPaperSizeLineOfEditor();
        }
    }
}
